package com.edu.controller.front;

import com.edu.controller.R;
import com.edu.entity.Student;
import com.edu.service.PaperService;
//import com.edu.service.ScoreDetailService;
//import com.edu.service.StuQuestionRecordsService;
import com.edu.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/StuUser")
public class StuUserController {
    //{1}自动装配 4 个对象。
    @Autowired
    private StudentService studentService;
    @Autowired
    private PaperService paperService;
//    @Autowired
//    private StuQuestionRecordsService recordsService;
//    @Autowired
//    private ScoreDetailService detailService;

    /* 1. 添加异常处理器  */
    @ExceptionHandler(value=Exception.class)
    @ResponseBody
    public String exceptionFallBack(Exception e){
        e.printStackTrace();
        return R.error(e).toJson();
    }

    /*
     * 2.注册学生账号信息
     *   Link: /StuUser/regStu (POST)
     *   映射地址: /regStu
     *   入参对象: Student
     *   返回数据: R(JSON)
     */
    @RequestMapping("/regStu")
    @ResponseBody
    public R regStu(Student student){
        studentService.regStu(student);
        return R.ok();
    }


    /*
        2.学生登录 [/StuUser/login]
        映射地址: /login
        入参对象: Student, HttpSession
        session域: stuUser
        返回数据: R(JSON)
        ps: 处理验证码
     */
    @RequestMapping("/login")
    @ResponseBody
    public R login(Student student, HttpSession session){
        //1.去session获取验证码
        String code = (String)session.getAttribute("code");
        //2.学生提交的验证码
        String usercode = student.getUsercode();
        if ( !usercode.equals(code)){
            return R.error("验证码错误");
        }
        //3.调用service去登录
        Student svStu = studentService.login(student);
        session.setAttribute("stuUser",svStu);
        return R.ok();
    }

    @RequestMapping("/logOut")
    public String logout(HttpSession session){
        session.removeAttribute("stuUser");
        session.invalidate();
        return "redirect:/Front/login";
    }

}



